package com.che.libcommon.api;

import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.Optional;
import io.reactivex.observers.ResourceSingleObserver;
import java.io.IOException;

/**
 * 用于处理可能为null
 * @param <T>
 */
public abstract class ApiOptionalResultObserver<T> extends ResourceSingleObserver<Optional<T>> {

  @Override
  public final void onSuccess(Optional<T> tOptional) {
    onApiResult(tOptional.orNull());
    onComplete();
  }

  protected abstract void onApiResult(@Nullable T t);

  @Override
  public void onError(Throwable e) {
    if(e instanceof ApiException){
      onApiError(((ApiException) e).getBaseResult());
    }else {
      BaseResult result = new BaseResult();
      if(e instanceof IOException){
        result.msg = "网络错误";
        result.statusCode = 4000;
      }
      result.error=e;
      onApiError(result);
    }
    onComplete();
  }

  protected abstract void onApiError(@Nullable BaseResult result);

  protected void toastErrorMsg(BaseResult result){
    if(result != null && !TextUtils.isEmpty(result.msg)){
      ToastUtils.showText(result.msg);
    }
  }

  protected void onComplete(){

  }

}
